package com.edgarli.common.utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @description:钉钉机器人通知
 * @author:EdgarLi
 * @date:2022-06-07 17:54
 **/

@Component
@Slf4j
public class DingTalkUtils {

    private static String webhook;

    @Value("${DingDing.webhook:#{null}}")
    public void setWebhook(String webhook) {
        DingTalkUtils.webhook = webhook;
    }


    /**
     * 关键字。
     */
    private static String keyword;

    @Value("${DingDing.keyword:#{null}}")
    public void setKeyword(String keyword) {
        DingTalkUtils.keyword = keyword;
    }

    /**
     * 被@人的用户userid。
     */
    private static String userIds;

    @Value("${DingDing.userIds:#{null}}")
    public void setUserIds(String userIds) {
        DingTalkUtils.userIds = userIds;
    }

    /**
     * 被@人的手机号。
     */
    private static String atMobiles;

    @Value("${DingDing.atMobiles:#{null}}")
    public void setAtMobiles(String atMobiles) {
        DingTalkUtils.atMobiles = atMobiles;
    }


    /**
     * 是否@所有人。
     */
    private static Boolean isAtAll;

    public static ObjectMapper objectMapper = new ObjectMapper();

    @Value("${DingDing.isAtAll:#{false}}")
    public void setIsAtAll(Boolean isAtAll) {
        DingTalkUtils.isAtAll = isAtAll;
    }

    static ExecutorService threadPool = new ThreadPoolExecutor(1, 2, 0, TimeUnit.SECONDS, new LinkedBlockingQueue<>());

    @SneakyThrows
    public static void sendErrorMsg(HttpServletRequest re, Exception error) {
        sendErrorMsg(re, error, "");
    }

    @SneakyThrows
    public static void sendErrorMsg(HttpServletRequest re, Exception error, String other) {
        HttpServletRequest httpServletRequest = re;
        String url = re.getRequestURI();
        String params = objectMapper.writeValueAsString(httpServletRequest.getParameterMap());
        String msg = "\n" + other + "\n" + "url： " + url + "\n参数： " + params + "\n异常：" + error.getClass().getSimpleName() + "\n原因：" + error.getMessage();
        sendMsg(msg);
    }

    public static void sendMsg(String msg) {
        if (StringUtils.isEmpty(webhook)) {
            return;
        }
        threadPool.execute(() -> {
            try {
                DingTalkClient client = new DefaultDingTalkClient(webhook);
                OapiRobotSendRequest request = new OapiRobotSendRequest();
                request.setMsgtype("text");
                OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
                text.setContent(keyword +"\n"+ msg);
                request.setText(text);
                OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
                if (StringUtils.hasLength(atMobiles)) {
                    at.setAtMobiles(Arrays.asList(atMobiles.split(",")));
                } else if (StringUtils.hasLength(userIds)) {
                    at.setAtUserIds(Arrays.asList(userIds.split(",")));
                } else {
                    isAtAll = true;
                }
                at.setIsAtAll(isAtAll);
                request.setAt(at);
                OapiRobotSendResponse response = client.execute(request);
            } catch (Exception e) {
                log.error("钉钉消息发送失败：" + e.getMessage());
            }
        });

    }

    public static void sendSqlErrorMsg(SQLException e) {
        String msg = "\n" + "state： " + e.getSQLState() + "\nCode： " + e.getErrorCode() + "\n异常：" + e.getClass().getSimpleName() + "\n原因：" + e.getMessage();
        sendMsg(msg);
    }
}
